// pages/mys/set/uname/index.js
const app = getApp(); // 获取应用实例
var Utils = require('../../../../utils/crypt.js'); //加密解密

Page({

  /**
   * 页面的初始数据
   */
  data: {
    uname: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUname();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //返回
  toBack: function () {
    console.log('返回')
    wx.showToast({
      title: '即将返回..', icon: 'none'
    })
    wx.redirectTo({
      url: '/pages/mys/set/index'
    })
  },
  //获取缓存昵称
  getUname: function () {
    var that = this;
    wx.getStorage({
      key: 'userInfo',
      success:res=> {
        console.log(res);
        var uname = res.data.uname;
        that.setData({uname:uname});
      },
      fail:err=>{
        console.log(err)
      },
    });
  },
  //同步昵称
  inputName: function (e) {
    console.log(e);
    var that = this;
    var uname = e.detail.value;
    that.setData({uname: uname});
  },
  //保存提交
  formSave: function (e) {
    console.log(e);
    var userInfo = wx.getStorageSync("userInfo");
    var uname = this.data.uname;
    var formData = {
      wx: app.globalData.usertest, uname: uname,
    };
    //请求数据
    wx.request({
      url: app.globalData.domain+'/my/user/uname/modify',
      method: "POST",
      header: {'content-type': 'application/x-www-form-urlencoded'},
      data: formData,
      success: function (res) {
        wx.hideLoading();
        if (res.data.code!=0) {
          wx.showToast({
            title: res.data.msg, icon: 'none',
          }); return
        } 
        wx.showToast({
          title: '保存成功..', icon: 'none',
        }); 
        if (!userInfo) {
          userInfo = {uname:uname};
        } else {
          userInfo.uname = uname;
        }
        wx.setStorageSync("userInfo", userInfo);
        setTimeout(function(){
          wx.redirectTo({
            url: '/pages/mys/set/index'
          });
        },2000);
      }
    });
  },
})